package com.tan.config;

import com.tan.pojo.User;
import com.tan.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 获取用户：Subject currentUser =SecurityUtils.getSubject()
 * 获得session： Session session = currentUser.getSession();
 * 判断当前用户是否被认证：currentUser.isAuthenticated()
 * 获得当前用户的认证（vip几级）：currentUser.getPrincipal()
 * 判断用户是否拥有什么角色：currentUser.hasRole("schwartz")
 * 判断用户的权限：currentUser.isPermitted("lightsaber:wield")
 * 注销：currentUser.logout();
 */

//自定义的Realm
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addStringPermission("user:add");全局授权

        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();//拿到User对象
        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthenticationInfo");


        UsernamePasswordToken usertoken = (UsernamePasswordToken) token;
        //连接真实数据库
        User user = userService.getUserByName(usertoken.getUsername());
        if(user==null)//没有这个人
        {
            return null;//报出异常
        }

//        Subject currentSubject = SecurityUtils.getSubject();
//        Session session = currentSubject.getSession();
//        session.setAttribute("loginUser",user);
        //可以键MD5
        //密码认证,shiro
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}
